package com.hsh.server.interceptor;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsh.server.constant.CustomException;
import com.hsh.server.constant.HttpStatus;
import com.hsh.server.project.user.entity.TAppUser;
import com.hsh.server.project.user.mapper.TAppUserMapper;
import com.hsh.server.project.userinfo.domain.TAppUserInfo;
import com.hsh.server.util.StringUtils;
import com.hsh.server.util.redis.JwtWithHutoolExample;
import com.hsh.server.util.redis.RedisConstants;
import com.hsh.server.util.redis.TokenServiceTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 拦截器
 *
 * @author
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {


    @Autowired
    private TokenServiceTask tokenServiceTask;
    private List<String> whiteList = Arrays.asList("/user/register","/user/appLogin","/user/test2","/system/info/appLogin","/system/info/register");


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        // 检查白名单
        if (whiteList.contains(requestURI)) {
            return true;
        }

        System.out.println("开始拦截 AuthInterceptor.........");

        String token = request.getHeader(UserUtils.TOKEN_KEY);
        //token是否存在
        if (StringUtils.isEmpty(token)) {
            throw new CustomException("token为空", HttpStatus.UNAUTHORIZED);
        }


        //解析token是否有效
        DecodedJWT decodedJWT = JwtWithHutoolExample.verifyJwt(token);
        if (decodedJWT == null)
            throw new CustomException("token无效", HttpStatus.UNAUTHORIZED);

        //验证token是否过期
        String tokenStr = tokenServiceTask.getToken(RedisConstants.LOGIN_USER_KEY + decodedJWT.getSubject());
        if (StringUtils.isEmpty(tokenStr))
            throw new CustomException("token已过期", HttpStatus.UNAUTHORIZED);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // JSON 字符串转 Java 对象
        TAppUserInfo deserializedUser = objectMapper.readValue(tokenStr, TAppUserInfo.class);
        UserUtils.setUserInfo(token,deserializedUser);
        String  jsonAccount ="";
        try {
            jsonAccount = objectMapper.writeValueAsString(deserializedUser);
        } catch (
                JsonProcessingException e) {
            e.printStackTrace();
            throw new CustomException("转换对象错误", HttpStatus.ERROR);
        }
//        tokenServiceTask.freshTime(RedisConstants.LOGIN_USER_KEY + decodedJWT.getSubject());
        tokenServiceTask.setTokenWithTime(RedisConstants.LOGIN_USER_KEY+ decodedJWT.getSubject(), jsonAccount, 43200, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成清除授权信息
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

    }


}
